<?php
declare (strict_types=1);

namespace app\api\controller;

use app\BaseController;
use app\common\traits\JumpTrait;
use think\exception\ValidateException;

class Base extends BaseController
{

    use JumpTrait;

    //每页展示条数
    protected $pagesize = 20;

    /**
     * api专用  返回值判断
     * @param $data
     * @return mixed
     */
    public function res($data)
    {
        if ($data['code'] == 200) {
            return $this->apiSuccess($data['message'], $data['data'], $data['code']);
        }
        return $this->apiFail($data['message'], $data['data'], $data['code']);
    }

    /**
     * Author:Zhongyuan Lu
     * Api成功返回
     * @param string $message
     * @param array $data
     * @param int $code
     */
    public function apiSuccess($message = '', $data = [], $code = 200)
    {
        return $this->result($data, $code, $message, 'json');
    }

    /**
     * Author:Zhongyuan Lu
     * Api失败返回
     * @param string $message
     * @param array $data
     * @param int $code
     */
    public function apiFail($message = '', $data = [], $code = 400)
    {
        return $this->result($data, $code, $message, 'json');
    }

    /**
     * validate验证器验证
     * @param array|string $params
     * @return array|string|true|void
     */
    public function validateFail($obj, $params)
    {
        //验证参数
        try {
            validate($obj)->batch(true)->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $msg = implode($e->getError(), ',');
            return $this->result([], 400, $msg, 'json');
        }
    }
}
